package com.sjd.common.utils;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import java.util.*;

/**
 * @ProjectName: sjd
 * @Package: com.sjd.common.utils
 * @ClassName: WxAppletUtil
 * @Author: genglong
 * @Description: 小程序工具类
 * @Date: 2022/1/11 14:22
 * @Version: 1.0
 */
public class WxAppletUtil {

    public static final String SIGN_TYPE_MD5 = "MD5";

    public static final String SIGN_TYPE_HMAC_SHA256 = "HMAC-SHA256";

    /**
     * 随机生成指定长度的数字串
     *
     * @param length length
     * @return object
     * @author zhaozhihai
     */
    public static String getRandomNum(int length) {
        // length表示生成字符串的长度
        String base = "0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String sign(Map<String, String> requestMap, String signType, String signKey) {
        String signStr = getSignStr(requestMap);
        String sign = null;
        if (SIGN_TYPE_MD5.equals(signType)) {
            sign = DigestUtils.md5Hex(signStr + "&key=" + signKey);
        } else if (SIGN_TYPE_HMAC_SHA256.equals(signType)) {
            Mac mac = HmacUtils.getInitializedMac(HmacAlgorithms.HMAC_SHA_256, signKey.getBytes());
            byte[] bytes = mac.doFinal(signStr.getBytes());
            sign = Hex.encodeHexString(bytes, true);
        }
        return sign;
    }

    /**
     * 获取微信签名字符串
     *
     * @param signMap
     * @return
     * @author zhaozhihai
     */
    public static String getSignStr(Map<String, String> signMap) {
        if (signMap == null) {
            return null;
        }
        List<String> keyList = new ArrayList<>(signMap.keySet());
        Collections.sort(keyList);

        StringBuilder signBuf = new StringBuilder();
        for (String key : keyList) {
            String value = signMap.get(key);
            if (StringUtils.isNotEmpty(value)) {
                signBuf.append("&").append(key).append("=").append(value);
            }
        }

        String signStr = signBuf.length() > 0 ? signBuf.substring(1) : null;
        return signStr;
    }
}
